<template>
  <div class="container">
    <!-- 登录框 -->
    <div class="login_panel">
      <div class="title">
        <h2>注册账号</h2>
      </div>
      <div class="login_form">
        <el-form ref="form" :rules="rules" :model="postUser" label-width="85px">
          <el-form-item label="注册邮箱:" prop="user_email">
            <el-input v-model="postUser.user_email"></el-input>
          </el-form-item>
          <el-form-item label="用户名:" prop="username">
            <el-input v-model="postUser.username"></el-input>
          </el-form-item>
          <el-form-item label="密码:" prop="user_password">
            <el-input
              type="password"
              v-model="postUser.user_password"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码:" prop="user_repassword">
            <el-input
              type="password"
              v-model="postUser.user_repassword"
            ></el-input>
          </el-form-item>
          <el-form-item label="验证码:" prop="reg_code">
            <el-row type="flex">
              <el-input
                type="text"
                :disabled="isInputDisabled"
                v-model="postUser.reg_code"
              ></el-input>
              <el-button
                type="primary"
                :disabled="isButtonDisabled"
                @click="sendRegCode"
                >{{ buttonText }}</el-button
              ></el-row
            >
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="validateForm('form')">注册</el-button>
            <el-button type="success" @click="backLogin">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import { sendRegCode, regUser } from "@/api";

export default {
  name: "RegView",
  data() {
    //验证两次密码一致性
    let validatePass = (rule,value,callback)=>{
        if(value!==this.postUser.user_password){
            callback(new Error('两次输入密码不一致'));
        }else{
            callback();
        }
    }
    return {
      postUser: {
        username: "",
        user_email: "",
        user_password: "",
        user_repassword: "",
        reg_code: "",
      },
      postRegCode: {
        user_email: "",
      },
      isInputDisabled: true, //默认验证码输入框不可用
      isButtonDisabled: false, //默认发送验证码按钮可用
      count: 10, //声明60秒倒计时
      timeRunning: false,
      timer: null,
      buttonText: "发送验证码",
      //验证规则
      rules: {
        user_email:[
            { required: true, message: "请输入邮箱", trigger: "blur" },
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 15, message: "长度再3到15个字符", trigger: "blur" },
        ],
        user_password:[
            { required: true, message: "请输入密码", trigger: "blur" },
        ],
        user_repassword:[
            { required: true, message: "请输入密码确认", trigger: "blur" },
            { validator : validatePass ,trigger: "blur"}
        ],
        reg_code:[
            { required: true, message: "请输入验证码", trigger: "blur" },
        ],
      },
    };
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    //发送验证码
    sendRegCode() {
      if (this.validateEmail()) {
        this.sendCodeHandler();
        this.isInputDisabled = false;
        this.isButtonDisabled = true;
        this.startCount();
      }
    },
    //调用后端接口发送邮件
    async sendCodeHandler() {
      let res = await sendRegCode(this.postUser);
      if (res.code == 200) {
        this.$message({
          message: res.msg,
          type: "success",
        });
      } else {
        this.$message.error(res.msg);
      }
    },
    //验证邮箱是否有效
    validateEmail() {
      // 定义邮箱的正则表达式
      const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
      // 使用正则表达式测试邮箱
      if (regex.test(this.postUser.user_email)) {
        return true;
      } else {
        this.$message.error("请输入有效的邮箱地址");
        return false;
      }
    },
    //倒计时
    startCount() {
      this.timeRunning = true;
      this.timer = setInterval(() => {
        if (this.count > 0) {
          this.buttonText = "请稍后" + this.count + "秒";
          this.count--;
        } else {
          this.stopCountdown();
          this.buttonText = "发送验证码";
          this.isButtonDisabled = false;
        }
      }, 1000);
    },
    stopCountdown() {
      clearInterval(this.timer);
      this.count = 60;
      this.timeRunning = false;
    },
    //注册前验证
    validateForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //前端验证成功，调用注册方法
          this.regUser();
        }else{
            return false;
        }
      });
    },
    //注册用户事件
    async regUser() {
      //注册用户
      let res = await regUser(this.postUser);
      if (res.code == 200) {
        this.$message({
          message: res.msg,
          type: "success",
        });
        //跳转登录页面
        this.$router.push("./login");
      } else {
        this.$message.error(res.msg);
      }
    },
    backLogin() {
      this.$router.push("./login");
    },
  },
};
</script>
<style scoped>
.container {
  display: flex;
  justify-content: center;
  height: 100vh;
  align-items: center;
}

.login_panel {
  width: 400px;
  height: 500px;
}

.title {
  display: flex;
  justify-content: center;
  height: 50px;
  align-items: center;
}
</style>